# 将原始图片转换成需要的大小，并将其保存
import os
import tensorflow as tf
from PIL import Image
from classification.config.Params import Params
import numpy as np


params = Params()


# 制作TFRecords数据
def create_record():
    train_sum = 0
    test_sum = 0
    train_writer = tf.python_io.TFRecordWriter("flower_train.tfrecords")
    test_writer = tf.python_io.TFRecordWriter("flower_test.tfrecords")
    for index, name in params.classes.items():
        class_path = params.orig_picture_path + name + "/"
        for img_name in os.listdir(class_path):
            img_path = class_path + img_name
            images = Image.open(img_path)
            images = images.resize(params.shape)  # 设置需要转换的图片大小
            img_raw = images.tobytes()  # 将图片转化为原生bytes
            print(index, img_raw)
            if np.random.rand() < 0.7:
                train_example = tf.train.Example(features=tf.train.Features(
                    feature={
                        "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
                        'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
                    }
                ))
                train_sum = train_sum + 1
                train_writer.write(train_example.SerializeToString())
                params.num_train = train_sum
            else:
                test_example = tf.train.Example(features=tf.train.Features(
                    feature={
                        "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
                        "img_raw": tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
                    }
                ))
                test_sum = test_sum + 1
                test_writer.write(test_example.SerializeToString())
                params.num_test = test_sum
    train_writer.close()
    test_writer.close()


def read_and_decode(filename):
    # 创建文件队列,不限读取的数量
    filename_queue = tf.train.string_input_producer([filename])
    # create a reader from file queue
    reader = tf.TFRecordReader()
    # reader从文件队列中读入一个序列化的样本
    _, serialized_example = reader.read(filename_queue)
    # get feature from serialized example
    # 解析符号化的样本
    features = tf.parse_single_example(
        serialized_example,
        features={
            'label': tf.FixedLenFeature([], tf.int64),
            'img_raw': tf.FixedLenFeature([], tf.string)
        })
    label = features['label']
    img = features['img_raw']
    img = tf.decode_raw(img, tf.uint8)
    img = tf.reshape(img, [64, 64, 3])
    # img = tf.cast(img, tf.float32) * (1. / 255) - 0.5
    label = tf.cast(label, tf.int32)
    return img, label


if __name__ == '__main__':
    if not os.path.exists(params.samples_path + "train"):
        os.makedirs(params.samples_path + "train")
    if not os.path.exists(params.samples_path + "test"):
        os.makedirs(params.samples_path + "test")
    create_record()
    train_batch = read_and_decode('flower_train.tfrecords')
    test_batch = read_and_decode('flower_test.tfrecords')
    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())

    with tf.Session() as sess:  # 开始一个会话
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for i in range(params.num_train):
            train_example, train_lab = sess.run(train_batch)  # 在会话中取出image和label
            img = Image.fromarray(train_example, 'RGB')
            image_name = "{0:0>5}_train_samples_{1}.jpg".format(str(i), str(train_lab))
            img.save(params.samples_path + 'train/' + image_name)
        for i in range(params.num_test):
            test_example, test_lab = sess.run(test_batch)
            img = Image.fromarray(test_example, 'RGB')
            image_name = "{0:0>5}_test_samples_{1}.jpg".format(str(i), str(test_lab))
            img.save(params.samples_path + 'test/' + image_name)

            # print(example, lab)
        coord.request_stop()
        coord.join(threads)
        sess.close()
